import * as user from '@/api/user';
import * as types from '../action-types';
import { setLocal, getLocal } from '@/utils/local';

import router from '@/router'
import per from '@/router/per.js'

const filterRouter = (authList)=>{
    let auths = authList.map(auth=>auth.auth);
    function filter(routes){
        return routes.filter(route=>{
            if(auths.includes(route.meta.auth)){
                if(route.children){
                    route.children = filter(route.children )
                }
                return route;
            }
        })
    }
    return filter(per)
}

export default {
  state: {
    userInfo: {},
    hasPermission: false,
    menuPermission:false,
  },
  mutations: {
    [types.SET_USER](state, userInfo) {
      state.userInfo = userInfo;
      if (userInfo && userInfo.token) {
        setLocal('token', userInfo.token);
      } else {
        localStorage.clear('token');
      }
    },
    [types.SET_PERMISSION](state, has) {
      state.hasPermission = has;
    },
    [types.SET_MENU_PERMISSION](state, has) {
      state.menuPermission = has;
    }
  },
  actions: {
    async [types.SET_USER]({ commit }, { payload, permission }) {
      commit(types.SET_USER, payload);
      commit(types.SET_PERMISSION, permission)
    },
    async [types.USER_LOGIN]({ commit, dispatch }, payload) {
      try {
        let result = await user.login(payload);
        dispatch(types.SET_USER, { payload: result.data, permission: true })
      } catch (e) {
        debugger
        this.$message('登录失败');
        return Promise.reject(e);
      }
    },
    async [types.USER_VALIDATE]({dispatch}){
      if(!getLocal('token')) return false;
      try{
          let result =  await user.validate();
          dispatch(types.SET_USER,{payload:result.data,permission:true});
          return true;
      }catch(e){  
          dispatch(types.SET_USER,{payload:{},permission:false});
          return false;
      }
    },
    async [types.USER_LOGOUT]({dispatch}){
      dispatch(types.SET_USER,{payload:{},permission:false})
    },
    async [types.ADD_ROUTE]({commit,state}){
      let authList = state.userInfo.authList; 
      if(authList){
        let routes = filterRouter(authList); 
        let route = router.options.routes.find(item=>item.path === '/manager');
        route.children = routes;
        router.addRoutes([route]);
        commit(types.SET_MENU_PERMISSION,true);
      }else{
        commit(types.SET_MENU_PERMISSION,true);
      }
    }
  }
}
